# @Time : 2020/7/30 15:03
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np

"""
line = cv.fitLine(points,distType,param,reps,aeps)
式中line为返回值,是返回的最优拟合直线参数
points是轮廓.
distType: 距离类型.拟合直线时,要使输入点到拟合直线的距离之和最小.其类型如下:
DIST_USER  用户自定义距离
DIST_L1  distance = |x1-x2| + |y1-y2|
DIST_L2  欧氏距离
DIST_C   distance = max(|x1-x2|,|y1-y2|)
DIST_L12 distance = 2(sqrt(1+x*x/2)-1)

param: 距离参数,与所选的距离类型有关.当此参数被设置为0的时候,该函数会自动选择最优值.
reps: 用于表示拟合直线所需要的径向精度,通常改值被设置为0.01
aeps: 用于表示拟合直线所需要的角度精度,通常该值被设定为0.01
"""
img = cv.imread("cc.bmp")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

cv.imshow("Original", img)
T, thres = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
image, contours, hierarchy = cv.findContours(thres, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
rows, cols = img.shape[:2]
[vx, vy, x, y] = cv.fitLine(contours[0], cv.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x * vy / vx) + y)
righty = int(((cols - x) * vy / vx) + y)

cv.line(img, (cols - 1, righty), (0, lefty), (0, 255, 0), 1)

cv.imshow("fitLine", img)
cv.waitKey(0)
